package com.yanchangapp.ui.activity.purchase.apply;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yanchangapp.R;
import com.yanchangapp.adapter.GoodsApplyAdapter;
import com.yanchangapp.commom.LoadingType;
import com.yanchangapp.model.bean.GoodsApplyBean;
import com.yanchangapp.model.request.SubmitApplyRequest;
import com.yanchangapp.ui.presenter.GoodsApplyAtPresenter;
import com.yanchangapp.ui.view.GoodsApplyAtView;
import com.yanchangapp.widget.SupplierListBottomDelegate;
import com.yanchangapp.widget.SupplierNumDialog;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.widget.YCLoadingView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
/**
 * 经营品种活动...
 */
public class GoodsApplyActivity extends BaseActivity<GoodsApplyAtView, GoodsApplyAtPresenter> implements GoodsApplyAtView {
    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.btnApprove)
    Button btnApprove;
    @BindView(R.id.tvProductSum)
    TextView tvProductSum;
    @BindView(R.id.bottom)
    RelativeLayout bottom;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.btnNextRefresh)
    TextView btnNextRefresh;
    @BindView(R.id.llErrorNetwork)
    LinearLayout llErrorNetwork;
    @BindView(R.id.ycLoading)
    YCLoadingView ycLoading;
    @BindView(R.id.tvDes)
    TextView tvDes;
    @BindView(R.id.llEmptyMsg)
    LinearLayout llEmptyMsg;
    private int curPage = 1;
    private int currentIndex;
    private GoodsApplyAdapter mGoodsApplyAdapter;
    private List<GoodsApplyBean> mGoodsApplyBeanList = new ArrayList<>();
    // 选中的供货商ID以及供货商姓名...
    private String selectSupplierId, selectSupplierName,tips,currentNum;
    private int mInnerRecommend;
    private int mSelectSize;
    private int mInnerSmall;
    private SupplierNumDialog mSupplierNumDialog;
    private SupplierListBottomDelegate.Builder mSupplierBuilder;

    public static void show(Activity activity) {
        Intent intent = new Intent(activity, GoodsApplyActivity.class);
        activity.startActivity(intent);
    }

    private void setLoadingState(LoadingType loadingType){
        switch (loadingType){
            case LOADING:
                if (ycLoading.getVisibility() == View.GONE){
                    ycLoading.setVisibility(View.VISIBLE);
                }

                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                }

                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }
                break;
            case SUCCESS:

                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (refreshLayout.getVisibility() == View.GONE){
                    refreshLayout.setVisibility(View.VISIBLE);
                    bottom.setVisibility(View.VISIBLE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }
                break;
            case ERROR:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.GONE){
                    llErrorNetwork.setVisibility(View.VISIBLE);
                }

                if (llEmptyMsg.getVisibility() == View.VISIBLE){
                    llEmptyMsg.setVisibility(View.GONE);
                }
                break;
            case EMPTY:
                if (ycLoading.getVisibility() == View.VISIBLE){
                    ycLoading.setVisibility(View.GONE);
                }

                if (refreshLayout.getVisibility() == View.VISIBLE){
                    refreshLayout.setVisibility(View.GONE);
                    bottom.setVisibility(View.GONE);
                }


                if (llErrorNetwork.getVisibility() == View.VISIBLE){
                    llErrorNetwork.setVisibility(View.GONE);
                }

                if (llEmptyMsg.getVisibility() == View.GONE){
                    llEmptyMsg.setVisibility(View.VISIBLE);
                }
            default:
                break;
        }
    }

    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_goods_apply;
    }

    @Override
    protected GoodsApplyAtPresenter createPresenter() {
        return new GoodsApplyAtPresenter(this);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("经营品种");
        initAdapter();
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        tvDes.setText("暂无经营品种");
        tvProductSum.setText(ResHelper.getString(R.string.bottom_goods_size, mSelectSize));
        bottom.setVisibility(View.GONE);
    }

    private void initAdapter() {
        mGoodsApplyAdapter = new GoodsApplyAdapter(R.layout.item_goods_apply, mGoodsApplyBeanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(mGoodsApplyAdapter);
    }

    @Override
    protected void initData() {
        loadList();
    }

    private void loadList() {
        // 滑动到了第一个....
        setLoadingState(LoadingType.LOADING);
        recyclerView.scrollToPosition(0);
        refreshList();
    }

    private void refreshList() {
        curPage = 1;
        refreshLayout.resetNoMoreData();
        mPresenter.quertList(curPage);
    }

    private void loadMore() {
        // 添加数量
        curPage++;
        mPresenter.quertList(curPage);
    }


    private void recallBackData(int innerNum) {
        GoodsApplyBean bean = mGoodsApplyBeanList.get(currentIndex);
        // 设置控件隐藏
        bean.setBuyNumber(innerNum);
        bean.setSupplierId(selectSupplierId);
        bean.setSupplierName(selectSupplierName);
        mSupplierNumDialog.dismiss();
        // 通知该列表项进行刷新
        mGoodsApplyAdapter.notifyItemChanged(currentIndex);
    }

    private void showSupplierBottom(){
        if (mSupplierBuilder == null){
            mSupplierBuilder = new SupplierListBottomDelegate.Builder(this)
                    .setDismissListener(this::showSupplierNumDialog)
                    .setEnsureListener((supplierID, supplierName) -> {
                        selectSupplierId = supplierID;
                        selectSupplierName = supplierName;
                    })
                    .create();
        }
        mSupplierBuilder.setData(mGoodsApplyBeanList.get(currentIndex).getSuppliers())
                .setSelectSupplier(selectSupplierId)
                .show();
    }

    @Override
    protected void initListener() {
        // 点击事件  进行返回...
        ivToolbarNavigation.setOnClickListener(v -> {
            finish();
        });
        mGoodsApplyAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.checkbox) {
                GoodsApplyBean bean = mGoodsApplyBeanList.get(position);
                bean.setSelected(!bean.isSelected());
                setBottomSelectSize();
            } else if (view.getId() == R.id.tvBuyShow) {
                if (mGoodsApplyBeanList.get(position).getPurchaseStatus() == 0){
                    return;
                }
                // 设置当前的position
                currentIndex = position;
                // 设置数据并进行显示
                GoodsApplyBean bean = mGoodsApplyBeanList.get(currentIndex);
                selectSupplierId = bean.getSupplierId();
                selectSupplierName = bean.getSupplierName();
                mInnerRecommend = bean.getRecommendNum();
                mInnerSmall = bean.getAlarmMin() - bean.getInventoryNumber() ;
                if (mInnerSmall < 0){
                    mInnerSmall = 0;
                }
                if (mInnerRecommend == 0) {
                    tips = "库存无法存放";
                } else {
                    tips = getString(R.string.apply_tips, mInnerSmall, mInnerRecommend);
                }
                currentNum = String.valueOf(bean.getBuyNumber());
                showSupplierNumDialog();
            }
        });

        mGoodsApplyAdapter.setOnItemClickListener((adapter, view, position) -> {
            String productId = mGoodsApplyBeanList.get(position).getProductId();
            int isThirdFlag = mGoodsApplyBeanList.get(position).getIsThirdFlag();
            GoodsDetailActivity.show(GoodsApplyActivity.this, productId,isThirdFlag);
        });

        refreshLayout.setOnRefreshListener(refreshLayout -> refreshList());

        refreshLayout.setOnLoadMoreListener(refreshLayout -> loadMore());

        // 提交订单请求....
        btnApprove.setOnClickListener(v -> checkDataAndSubmit());


        // 刷新事件
        btnNextRefresh.setOnClickListener(v -> {
            // 如果请求失败再进行刷新
            initData();
        });
    }

    private void showSupplierNumDialog() {
        mSupplierNumDialog = new SupplierNumDialog.Builder(this)
                .setBuyNum(currentNum)
                .setTipsString(tips)
                .setBuyRange(mInnerSmall, mInnerRecommend)
                .setSupplierName(selectSupplierName)
                .setEnsureListener(this::recallBackData)
                .setJumpSupplierListener(numStr -> {
                    currentNum = numStr;
                    showSupplierBottom();
                }).build();
        mSupplierNumDialog.show();
    }

    /**
     * 检查数据并且重新提交订单...
     */
    private void checkDataAndSubmit() {
        if (mSelectSize == 0) {
            UIUtils.showToast("请选择经营品种");
            return;
        }
        List<SubmitApplyRequest> submitBeans = new ArrayList<>();
        for (int i = 0; i < mGoodsApplyBeanList.size(); i++) {
            GoodsApplyBean applyBean = mGoodsApplyBeanList.get(i);
            if (applyBean.isSelected()) {
                if (applyBean.getBuyNumber() == 0) {
                    UIUtils.showToast("请取消采购数量为0的品种");
                    return;
                } else {
                    submitBeans.add(new SubmitApplyRequest(
                            applyBean.getProductId(),
                            applyBean.getSupplierId(),
                            applyBean.getBuyNumber(),
                            applyBean.getPurchaseStatus(),
                            applyBean.getStoreRoomId(),
                            applyBean.getIsThirdFlag()));
                }
            }
        }
        mPresenter.submitApplyList(submitBeans);
    }

    /**
     * 设置底部的选择事件
     */
    public void setBottomSelectSize() {
        mSelectSize = 0;
        for (int i = 0; i < mGoodsApplyBeanList.size(); i++) {
            if (mGoodsApplyBeanList.get(i).isSelected()) {
                mSelectSize++;
            }
        }
        tvProductSum.setText(ResHelper.getString(R.string.bottom_goods_size, mSelectSize));
    }

    @Override
    public void queryListSuccess(List<GoodsApplyBean> mApplyBeans,boolean hasMore) {
        if (curPage == 1) {
            Log.e("列表刷新", "进来了");
            mGoodsApplyBeanList.clear();
            refreshLayout.finishRefresh();
            if (mApplyBeans == null || mApplyBeans.size() == 0) {
                setLoadingState(LoadingType.EMPTY);
                bottom.setVisibility(View.GONE);
            } else {
                setLoadingState(LoadingType.SUCCESS);
                mGoodsApplyBeanList.addAll(mApplyBeans);
                bottom.setVisibility(View.VISIBLE);
            }
            mGoodsApplyAdapter.notifyDataSetChanged();
        } else {
            if (mApplyBeans == null || mApplyBeans.size() == 0) {
                // 下拉加载无更多内容
                refreshLayout.finishLoadMoreWithNoMoreData();
                curPage--;
            } else {
                // 含有内容
                mGoodsApplyBeanList.addAll(mApplyBeans);
                mGoodsApplyAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadMore();
            }
        }
        setBottomSelectSize();
        Log.e("刷新", "是否含有更多数据:"+hasMore );
        if (!hasMore){
            refreshLayout.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void queryListFailure(String err) {
        if (curPage == 1) {
            refreshLayout.finishRefresh();
        } else {
            curPage--;
            refreshLayout.finishLoadMore();
        }
        if (mGoodsApplyBeanList == null || mGoodsApplyBeanList.size() == 0){
            setLoadingState(LoadingType.ERROR);
        }
    }

    // 经营品种提交成功的回调...
    @Override
    public void submitApplySuccess() {
        UIUtils.showToast("提交成功");
        mSelectSize = 0;
        // 重新请求一遍数据....
        initData();
    }

    @Override
    public void submitApplyFailure(String err) {
        UIUtils.showToast(err, Toast.LENGTH_LONG);
    }

}
